﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace EHR.Ctrls.QueryDesign
{
    public partial class OrderByPanel : UserControl
    {
        public OrderByPanel()
        {
            InitializeComponent();
        }

        private IList<ColInfo> Cols
        {
            get 
            {
                return cmbCol1.ItemsSource as IList<ColInfo>;
            }
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            
        }

        public void SetColumns(IList<ColInfo> cols)
        {
            IList<ColInfo> list = new List<ColInfo>();
            list.Add(new ColInfo() { DisplayName = " ", FieldName = " " });
            AddRang(cols, list);
            cmbCol1.ItemsSource = list;
            cmbCol2.ItemsSource = list;
        }

        private void AddRang(IList<ColInfo> source, IList<ColInfo> target)
        {
            foreach (ColInfo i in source)
            {
                target.Add(i);
            }
        }

        public void SetOrderBys(IList<OrderByInfo> orderBys)
        {
            if (orderBys.Count == 0)
            {
                return;
            }

            if (orderBys.Count > 0)
            {
                cmbCol1.SelectedIndex = FindIndex(orderBys[0].FieldName);
                ascOrder1.SelectedIndex = orderBys[0].IsAsc ? 0 : 1;
            }

            if (orderBys.Count > 1)
            {
                cmbCol2.SelectedIndex = FindIndex(orderBys[1].FieldName);
                ascOrder2.SelectedIndex = orderBys[1].IsAsc ? 0 : 1;
            }
        }

        public IList<OrderByInfo> GetOrderBys()
        {
            IList<OrderByInfo> list = new List<OrderByInfo>();
            if(cmbCol1.SelectedIndex > 0)
            {
                list.Add(new OrderByInfo() { FieldName = cmbCol1.SelectedValue as string, IsAsc = ascOrder1.SelectedIndex == 0 });
            }
            if (cmbCol2.SelectedIndex > 0)
            {
                list.Add(new OrderByInfo() { FieldName = cmbCol2.SelectedValue as string, IsAsc = ascOrder2.SelectedIndex == 0 });
            }

            return list;
        }

        private int FindIndex(string fieldName)
        {
            for (int i = 0; i < Cols.Count; i++)
            {
                ColInfo col = Cols[i];
                if (col.FieldName == fieldName)
                {
                    return i;
                }
            }

            return 0;
        }
    }
}
